import { type NitroFetchRequest } from 'nitropack'
import {
  getCachedData,
  getHashByOptions,
  onRequest,
  onResponse,
  onResponseError,
  transformResponse,
} from '@/service/apiFetch'
import type { ServerApiOptions } from '@/types/api.types'

function useServerApi<T = unknown, R extends NitroFetchRequest = NitroFetchRequest>(
  request: Parameters<typeof $fetch<T, R>>[0],
  options?: Partial<Parameters<typeof $fetch<T, R>>[1] & ServerApiOptions>,
) {
  const hash = getHashByOptions(request, options)
  const { data, status, error, refresh, clear } = useAsyncData<T, R>(
    hash,
    () =>
      $fetch(request, {
        ...options,
        onRequest,
        onResponse,
        onResponseError,
      }),
    {
      transform: transformResponse,
      getCachedData: (k, nuxt) => getCachedData(k, nuxt, options?.cacheTime),
    },
  )
  return {
    data,
    status,
    error,
    refresh,
    clear,
  }
}

export default useServerApi
